package com.css.fxfzaqbz.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Component
public class ExcelUtil {

    public static <R> File createExcel(List<R> dataList, List<ExcelAlias> aliasList, String destFilePath) {
        ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(destFilePath);
        for (ExcelAlias excelAlias : aliasList) {
            writer.addHeaderAlias(excelAlias.getField(), excelAlias.getOutTitle());
        }
        writer.setOnlyAlias(true);
        writer.write(dataList, true);
        setSizeColumn(writer.getSheet(), 8);
        writer.close();
        return new File(destFilePath);
    }

    /**
     * Excel导出
     *
     * @param dataList         数据列表（要导出的数据）
     * @param aliasList        数据别名（排序标题）
     * @param responseFileName 要导出的文件的名称
     * @param response
     * @param <R>
     */
    public static <R> void exportExcel(List<R> dataList, List<ExcelAlias> aliasList, String responseFileName, HttpServletResponse response) {
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + responseFileName + ".xlsx");
            response.setContentType("application/octet-stream;charset=utf-8");
            ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
            for (ExcelAlias excelAlias : aliasList) {
                writer.addHeaderAlias(excelAlias.getField(), excelAlias.getOutTitle());
            }
            writer.setOnlyAlias(true);
            writer.write(dataList, true);
            com.css.fxfzaqbz.util.ExcelUtil.setSizeColumn(writer.getSheet(), 8);
            writer.flush(outputStream, true);
            writer.close();
            IoUtil.close(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public <R> void exportExcelAndZip(List<R> dataList, String putFileName, Map<String, String> aliasMap, AttachmentInfoService attachmentInfoService, HttpServletResponse response, String... fileFileds) {
//        try (ServletOutputStream outputStream = response.getOutputStream()) {
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + putFileName + ".xlsx");
//            response.setContentType("application/octet-stream;charset=utf-8");
//            for (R r : dataList) {
//                JSONObject rJSONObj = JSONObject.parseObject(JSONObject.toJSONString(r));
//                for (String fileFiled : fileFileds) {
//                    String fileId = rJSONObj.get(fileFiled).toString();
//                    AttachmentInfoEntity attach = attachmentInfoService.getAttach(fileId);
//                    String attachPath = attach.getAttachPath();
//
//                }
//            }
//            ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
//            Set<Map.Entry<String, String>> aliasEntrySet = aliasMap.entrySet();
//            for (Map.Entry<String, String> aliasEntry : aliasEntrySet) {
//                writer.addHeaderAlias(aliasEntry.getKey(), aliasEntry.getValue());
//            }
//            writer.setOnlyAlias(true);
//            writer.write(dataList, true);
//            setSizeColumn(writer.getSheet(), 8);
//            writer.flush(outputStream, true);
//            writer.close();
//            IoUtil.close(outputStream);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 自适应宽度(中文支持)
     *
     * @param sheet sheet
     * @param size  因为for循环从0开始，size值为 列数-1
     */
    public static void setSizeColumn(Sheet sheet, int size) {
        for (int columnNum = 0; columnNum <= size; columnNum++) {
            int columnWidth = sheet.getColumnWidth(columnNum) / 256;
            for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row currentRow;
                //当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(columnNum) != null) {
                    Cell currentCell = currentRow.getCell(columnNum);
                    if (currentCell.getCellType() == CellType.STRING) {
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }
                }
            }
            sheet.setColumnWidth(columnNum, columnWidth * 256);
        }
    }

    public static class ExcelAlias {
        private String field;
        private String outTitle;

        public ExcelAlias(String field, String outTitle) {
            this.field = field;
            this.outTitle = outTitle;
        }

        public String getField() {
            return field;
        }

        public void setField(String field) {
            this.field = field;
        }

        public String getOutTitle() {
            return outTitle;
        }

        public void setOutTitle(String outTitle) {
            this.outTitle = outTitle;
        }
    }
}
